﻿using System;
using System.Collections.Generic;
using ETModel;

namespace ETHotfix
{
    /// <summary>
    /// 游戏内容级配置管理<para/>
    /// Config组件会扫描所有的有ConfigAttribute标签的配置,加载进来<para/>
    /// AddComponent&lt;ConfigComponent, string&gt;(ConfigFileInfo)<para/>
    /// ConfigFileInfo:<para/>
    ///     服务端传入配置文件相对运行目录的目录,结尾需要带"/"<para/>
    ///     客户端传入格式:bundleName|prefabName,如"config.unity3d|Config"<para/>
    /// </summary>
    public class ConfigComponent: Component {
        public Dictionary<Type, ACategory> AllConfig = new Dictionary<Type, ACategory>();

        public ConfigType GetOne<ConfigType>()
            where ConfigType : class, IConfig {
            Type cfgType = typeof(ConfigType);
            ACategory configCategory;
            if (!AllConfig.TryGetValue(cfgType, out configCategory)) {
                throw new Exception($"ConfigComponent not found key: {cfgType.FullName}");
            }
            return configCategory.GetOne<ConfigType>();
        }

        public ConfigType Get<ConfigType>(long id)
            where ConfigType : class, IConfig {
            Type cfgType = typeof(ConfigType);
            ACategory configCategory;
            if (!AllConfig.TryGetValue(cfgType, out configCategory)) {
                throw new Exception($"ConfigComponent not found key: {cfgType.FullName}");
            }

            return configCategory.TryGet<ConfigType>(id);
        }

        public ConfigType TryGet<ConfigType>(long id)
            where ConfigType : class, IConfig {
            Type cfgType = typeof(ConfigType);
            ACategory configCategory;
            if (!AllConfig.TryGetValue(cfgType, out configCategory)) {
                return null;
            }
            return configCategory.TryGet<ConfigType>(id);
        }

        public ConfigType[] GetAll<ConfigType>()
            where ConfigType : class, IConfig {
            Type cfgType = typeof(ConfigType);
            ACategory configCategory;
            if (!AllConfig.TryGetValue(cfgType, out configCategory)) {
                throw new Exception($"ConfigComponent not found key: {cfgType.FullName}");
            }
            return configCategory.GetAll<ConfigType>();
        }

        public CategoryType GetCategory<CategoryType, ConfigType>()
            where CategoryType : ACategory<ConfigType>
            where ConfigType : class, IConfig {
            Type cfgType = typeof(ConfigType);
            ACategory configCategory;
            bool ret = AllConfig.TryGetValue(cfgType, out configCategory);
            return ret ? configCategory as CategoryType : null;
        }

    }
}